/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-08-29
 * Time: 14:50
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution5 {
    public ListNode reverseKGroup(ListNode head, int k) {
        // 1.先求出需要逆序多少组
        ListNode cur = head;
        int n = 0;
        while(cur != null) {
            cur = cur.next;
            n++;
        }
        n /= k;

        // 2.重复n次长度为k的链表逆序
        ListNode newHead = new ListNode(0);
        ListNode prev = newHead;
        cur = head;
        for(int i = 0; i < n; i++) {
            // 记录每组开头
            ListNode tmp = cur;
            for(int j = 0; j < k; j++) {
                ListNode cur1 = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = cur1;
            }
            prev = tmp;
        }
        // 把后面不需要连上
        prev.next = cur;
        return newHead.next;
    }
}